//
//  ExcellentPlay.m
//  Courses
//
//  Created by YiXuePxh on 15/5/20.
//  Copyright (c) 2015年 boyibang. All rights reserved.
//

#import "ExcellentPlay.h"
#import "WTFColors.h"
#import "LTCMoviePlayerController.h"
#define TIME 300
#import "LeTVRecord.h"
#import <ShareSDK/ShareSDK.h>
#import "ExcellentPlayModel.h"
#include "ExcellentViewController.h"
@interface ExcellentPlay ()<LTCMoviePlayerControllerDelegate,UIScrollViewDelegate>
{
    LTCPlayerStreamType _livingPlayerType;
    UIScrollView* _scrollview;
    CGFloat _recommendHeight;
    CGSize _screenSize;
    NSMutableArray* _recomList;
    UILabel* _teacher;
    UILabel* _time;
    UILabel* _intro;
    CGFloat _ratio;
}
@property(nonatomic,strong)LTCMoviePlayerController* moviePlayerController;
@property (nonatomic, assign) BOOL m_bScreen;

//@property (strong, nonatomic) IBOutlet UIButton *reviewLog;
//@property (strong, nonatomic) IBOutlet UIButton *playBtn;
//@property (strong, nonatomic) IBOutlet UIButton *PauseBtn;
//@property (nonatomic, strong) DebugViewController *debugViewController;
@property (nonatomic, strong) UIView * gestureView;
@property (nonatomic, assign) LTCplayerType type;
//@property (strong, nonatomic) IBOutlet UIButton *stopBtn;

@property (nonatomic, strong) NSArray *valibCodeArray; // 可用的码流信息

@property (nonatomic, strong) NSString *liveId;
@property (nonatomic, strong) NSString *userUnique;
@property (nonatomic, strong) NSString *videoUnique;
@property (nonatomic, assign) BOOL autoPlay;
@property (nonatomic, assign) NSInteger startPlayTime;
@property (nonatomic, strong) NSString *liveName;
@property(nonatomic,assign)float backTime;

@property (nonatomic, assign) BOOL Support_UserRote;
@property(nonatomic,strong)NSTimer* timer;
@end

@implementation ExcellentPlay
-(instancetype)initWithType:(LTCplayerType)type{
    if (self = [super init]) {
        self.type = type;
        _Support_UserRote = NO;
    }
    return self;
}
-(BOOL)prefersStatusBarHidden{
    return YES;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _ratio = [UIScreen mainScreen].bounds.size.width / 320.0;
    CGSize screenSize = [UIScreen mainScreen].bounds.size;
    self.tabBarController.tabBar.backgroundColor = [UIColor blueColor];
    //label界面添加
    [self showWordView];
    //加载乐视
    [self LeTVDidLoad];
    //
    //返回界面
    UIView* floatView = [[UIView alloc]initWithFrame:CGRectMake(0, screenSize.height - 44, screenSize.width, 44)];
    [self.view addSubview:floatView];
    floatView.backgroundColor = [WTFColors defaultBarColor];
    UIButton* backBtn = [[UIButton alloc]initWithFrame:CGRectMake(14, 0, 44, 44)];
    [floatView addSubview:backBtn];
    [backBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    [backBtn setImage:[UIImage imageNamed:@"backImage.png"] forState:UIControlStateNormal];
    UIButton* shareBtn = [[UIButton alloc]initWithFrame:CGRectMake(screenSize.width - 14 - 44, 0, 44, 44)];
    [floatView addSubview:shareBtn];
    [shareBtn setImage:[UIImage imageNamed:@"shareImage.png"] forState:UIControlStateNormal];
    [shareBtn addTarget:self action:@selector(shareAction:) forControlEvents:UIControlEventTouchUpInside];
    //返回界面结束
    //观看时间统计
    _timer = [NSTimer scheduledTimerWithTimeInterval:TIME target:self selector:@selector(timeAction) userInfo:nil repeats:YES];
}
-(void)showWordView{
    _screenSize = [UIScreen mainScreen].bounds.size;
    _scrollview = [[UIScrollView alloc]init];
    _scrollview.delegate = self;
    [_scrollview setHidden:NO];
    [self.view addSubview:_scrollview];
    UILabel* courseName = [[UILabel alloc]initWithFrame:AutoRectMake(12, 5, DEFAULT_WIDTH, 15, WTFAutoLayoutTypeText)];
    courseName.text = @"课程名称";
    courseName.font = [UIFont fontWithName:@"" size:15];
    [_scrollview addSubview:courseName];
    
    _teacher = [[UILabel alloc]initWithFrame:AutoRectMake(12, 25, 160, 20, WTFAutoLayoutTypeText)];
    _teacher.text = [NSString stringWithFormat:@"讲师：%@",_coutrse.teacher];
    _teacher.font = [UIFont fontWithName:nil size:13];
    [_scrollview addSubview:_teacher];
    
    _time = [[UILabel alloc]initWithFrame:AutoRectMake(130, 25, DEFAULT_WIDTH - 114, 20, WTFAutoLayoutTypeText)];
    _time.font = [UIFont fontWithName:nil size:13];
    _time.text = _coutrse.time;
    [_scrollview addSubview:_time];
    
    UILabel* courseIntro = [[UILabel alloc]initWithFrame:AutoRectMake(12, 46, DEFAULT_WIDTH, 15, WTFAutoLayoutTypeText)];
    courseIntro.font = [UIFont fontWithName:@"" size:15];
    courseIntro.text = @"课程简介";
    [_scrollview addSubview:courseIntro];
    
    _intro = [[UILabel alloc]initWithFrame:AutoRectMake(12, 65, DEFAULT_WIDTH - 24, 3200, WTFAutoLayoutTypeText)];
    _intro.numberOfLines = 0;
    _intro.font = [UIFont fontWithName:nil size:13];
    _intro.text = [NSString stringWithFormat:@"  %@",_coutrse.courseIntro];
    [_intro sizeToFit];
    [_scrollview addSubview:_intro];
    //添加灰色的线
    [self addLineViewWithHeight:AutoFloat(65 + _intro.size.height + 5)];
    _recommendHeight = 65 + _intro.size.height + 5;
    //设置滚动
    _scrollview.frame = CGRectMake(0, 180 * _ratio, _screenSize.width, _screenSize.height - 180 - 44);
    //精心推荐模块
    [self recommendView];
}
-(void)addLineViewWithHeight:(CGFloat)height{
    UIView* line = [[UIView alloc]initWithFrame:AutoRectMake(0, height, DEFAULT_WIDTH * _ratio, 1, WTFAutoLayoutTypeText)];
    [_scrollview addSubview:line];
    line.backgroundColor = [UIColor grayColor];
}
-(void)recommendView{
    UILabel* recom = [[UILabel alloc]initWithFrame:AutoRectMake(12, _recommendHeight + 7, DEFAULT_WIDTH - 180, 15, WTFAutoLayoutTypeText)];
    recom.text = @"精心推荐";
    recom.font = [UIFont fontWithName:@"" size:15];
    [_scrollview addSubview:recom];
    //更多button
//    UIButton* more = [[UIButton alloc]initWithFrame:AutoRectMake(DEFAULT_WIDTH - 50, _recommendHeight + 7, 40, 15, WTFAutoLayoutTypeText)];
//    [_scrollview addSubview:more];
//    [more setTitle:@"更多" forState:UIControlStateNormal];
//    [more setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//    [more addTarget:self action:@selector(moreAction) forControlEvents:UIControlEventTouchUpInside];
    //推荐页面
    UIView* recomView = [[UIView alloc]initWithFrame:AutoRectMake(0, _recommendHeight + 7 + 20, _screenSize.width, 210, WTFAutoLayoutTypeText)];
    [_scrollview addSubview:recomView];
    //获取精心推荐的详细列表
   
    if ([_coutrse.recommed isKindOfClass:[NSArray class]]) {
        _recomList = [[NSMutableArray alloc]init];
        for (id json in _coutrse.recommed) {
            ExcellentPlayModel* model = [ExcellentPlayModel getExcellentPlayModelByJson:json];
            [_recomList addObject:model];
        }
    }else{
        _recomList = nil;
    }
    NSLog(@"recomList%lu",(unsigned long)_recomList.count);
    //
    //添加视频button
    for (int i = 0; i < _recomList.count; i++) {
        UIButton* otherRecomBtn = [[UIButton alloc]initWithFrame:AutoRectMake((_screenSize.width / 2.78) * (i%3) + 5 * _ratio, 10 + (i/3) * 105, 90, 57, WTFAutoLayoutTypeText)];
        [otherRecomBtn setImage:[UIImage imageNamed:[_recomList[i] picName]] forState:UIControlStateNormal];
        [otherRecomBtn addTarget:self action:@selector(otherBntAction:) forControlEvents:UIControlEventTouchUpInside];
        otherRecomBtn.tag = i;
//        otherRecomBtn.titleLabel.text = [_recomList[i] videoId];
        [recomView addSubview:otherRecomBtn];
        
        UILabel* courseName = [[UILabel alloc]initWithFrame:AutoRectMake((_screenSize.width / 2.78) * (i%3) + 5 * _ratio, 70 + (i/3) * 105, 90, 30, WTFAutoLayoutTypeText)];
        courseName.text = [_recomList[i] className];
        courseName.font = [UIFont fontWithName:nil size:12];
        courseName.numberOfLines = 2;
        [courseName sizeToFit];
        [courseName setTextAlignment:NSTextAlignmentCenter];
        [recomView addSubview:courseName];
        
        UIImageView* count = [[UIImageView alloc]initWithFrame:AutoRectMake((_screenSize.width / 2.78) * (i%3) + 15 + 5 * _ratio, 100 + (i/3) * 105, 15, 15, WTFAutoLayoutTypeText)];
        count.image = [UIImage imageNamed:@"count.png"];
        [recomView addSubview:count];
        
        UILabel* countLabel = [[UILabel alloc]initWithFrame:AutoRectMake((_screenSize.width / 2.78) * (i%3) + 30 + 5 * _ratio, 102 + (i/3) * 105, 55, 15, WTFAutoLayoutTypeText)];
        countLabel.text = [NSString stringWithFormat:@"%@",[_recomList[i] watchCount] ];
        countLabel.font = [UIFont fontWithName:nil size:12];
        [recomView addSubview:countLabel];
    }
    _scrollview.contentSize = CGSizeMake(_screenSize.width, _recommendHeight + 300);
}
-(void)otherBntAction:(UIButton* )sender{
    NSLog(@"OTHER BNT");
    [_moviePlayerController releasePlayer];
    ExcellentPlayModel* playModel = _recomList[sender.tag];
    [self getVodInPutMessage:@"a821022973" VideoId:playModel.videoId ap:YES];
    
    _teacher.text = [NSString stringWithFormat:@"讲师：%@",playModel.teacher];
    _time.text =  playModel.time;
    _intro.text = [NSString stringWithFormat:@"  %@",playModel.courseIntro];
    [self LeTVDidLoad];
}
-(void)moreAction{
    NSLog(@"更多按钮");
    [_moviePlayerController releasePlayer];
    [self presentViewController:[ExcellentViewController sharedInstance] animated:NO completion:^{
    }];
}
-(void)timeAction{
    NSLog(@"记时啦   。。。。。");
    if ([User isLoggedIn]) {
        [LeTVRecord recordDataByVideoSourse:@"2" UserId:[User currentUser].userId CourseType:@"2" CourseId:@"2" LesssonId:_videoUnique VideoId:_videoUnique YxName:[User currentUser].userName];
    }else{
        [LeTVRecord recordDataByVideoSourse:@"2" UserId:@"YK" CourseType:@"2" CourseId:@"2" LesssonId:_videoUnique VideoId:_videoUnique YxName:@"YXYK"];
    }
}
- (void)didReceiveMemoryWarning {
    
    
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)backAction{
    NSLog(@"-----back");
    [_moviePlayerController releasePlayer];
    [self dismissViewControllerAnimated:YES completion:nil];
}
-(void)shareAction:(id)sender{
    NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"ShareSDK" ofType:@"png"];
    
    //构造分享内容
    id<ISSContent> publishContent = [ShareSDK content:@"股票操盘培训视频尽在益学堂官网www.yxcps.cn，免费观看，快来一起get赚钱新技能~~"
                                       defaultContent:@"分享消息"
                                                image:[ShareSDK imageWithPath:imagePath]
                                                title:@"上海益学堂"
                                                  url:@"http://www.yxcps.cn/index"
                                          description:@"这是益学堂分享给用户的信息"
                                            mediaType:SSPublishContentMediaTypeNews];
    //创建弹出菜单容器
    id<ISSContainer> container = [ShareSDK container];
    [container setIPadContainerWithView:sender arrowDirect:UIPopoverArrowDirectionUp];
    
    //弹出分享菜单
    [ShareSDK showShareActionSheet:container
                         shareList:nil
                           content:publishContent
                     statusBarTips:YES
                       authOptions:nil
                      shareOptions:nil
                            result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
                                
                                if (state == SSResponseStateSuccess)
                                {
                                    NSLog(NSLocalizedString(@"TEXT_ShARE_SUC", @"分享成功"));
                                }
                                else if (state == SSResponseStateFail)
                                {
                                    NSLog(NSLocalizedString(@"TEXT_ShARE_FAI", @"分享失败,错误码:%d,错误描述:%@"), [error errorCode], [error errorDescription]);
                                }
                            }];
    
}
//乐视播放器部分


//- (void)viewWillAppear:(BOOL)animated{
//}

//- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil type:(LTCplayerType) type
//{
//    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
//    if (self) {
//        self.type = type;
//        _Support_UserRote = NO;
//        // Custom initialization
//    }
//    return self;
//}


//- (void)clickStop:(id)sender{
//    if (self.type == LTCplayerTypeStreaming) {
//        [_moviePlayerController releasePlayer];
//        _moviePlayerController = nil;
//    }
//}

//- (IBAction)playBntClicked:(id)sender {
//    if (_moviePlayerController) {
//        [_moviePlayerController play];
//    }
//}

//- (IBAction)pauseClicked:(id)sender {
//    if (_moviePlayerController) {
//        [_moviePlayerController pause];
//    }
//}


//- (IBAction)clickToReviewLogs:(id)sender {
//    if (self.type == LTCplayerTypeStreaming) {
//        
//    }
//    if (!self.debugViewController) {
//        self.debugViewController = [[DebugViewController alloc] init];
//    }
//    [self.view addSubview:self.debugViewController.view];
//    self.debugViewController.view.frame = self.view.bounds;
//    [self.debugViewController setDesc:[_moviePlayerController getLTCPlayerDebugLog]];
//}
//- (IBAction)returnBack:(id)sender {
//    [_moviePlayerController releasePlayer];
//    [self.navigationController popViewControllerAnimated:YES];
//}



//- (void) viewWillDisappear:(BOOL)animated {
//    [super viewWillDisappear:animated];
//}
#pragma mark - public

//- (void) getlivingInputMessage:(NSString *)liveId playerType:(LTCPlayerStreamType)type liveName:(NSString *)liveName {
//    self.liveId = liveId;
//    _livingPlayerType = type;
//    _liveName = liveName;
//}

- (void) getVodInPutMessage:(NSString *)uuId VideoId:(NSString *)videoId ap:(BOOL)ap{
    self.userUnique = uuId;
    self.videoUnique = videoId;
    self.autoPlay = ap;
    float time = [[[NSUserDefaults standardUserDefaults]objectForKey:videoId] floatValue];
    self.startPlayTime = time;
}

- (void)LeTVDidLoad{
    if (self.type == LTCplayerTypeNormal) {
        
        _moviePlayerController = [[LTCMoviePlayerController alloc] initWithUserId:self.userUnique videoId:self.videoUnique movieSourceType:LTCMovieSourceTypeNormal];
        _moviePlayerController.startPlayBackTime = _startPlayTime;
        
    }else if (self.type == LTCplayerTypeStreaming){
        
        _moviePlayerController = [[LTCMoviePlayerController alloc] initWithLivingVideoId:self.liveId
                                                                                streamId:nil
                                                                               videoName:_liveName movieSourceType:LTCMovieSourceTypeStreaming playerDecodeType:_livingPlayerType];
    }
    _moviePlayerController.delegate = self;
    [self.view addSubview:_moviePlayerController.playerView];
}

- (void)loadGestureView{
    
}
- (void)viewWillLayoutSubviews {
    
    if (UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation)) {
        _m_bScreen = NO;
        
        CGFloat height = 0;
        CGFloat width = 0;
        if ([[UIDevice currentDevice].systemVersion floatValue]>8.0) {
            height = [UIScreen mainScreen].bounds.size.width;
            width = [UIScreen mainScreen].bounds.size.height;
        }else{
            height = [UIScreen mainScreen].bounds.size.height;
            width = [UIScreen mainScreen].bounds.size.width;
        }
        _moviePlayerController.playerView.frame = CGRectMake(0, 0, height, width);
        _moviePlayerController.controlStyle = LTCMovieControlStyleFullscreen;
        //        _gestureView.frame = CGRectMake(0, 0, 0, 0);
    }else{
        CGFloat width = [UIScreen mainScreen].bounds.size.width;
        _m_bScreen = YES;
        _moviePlayerController.playerView.frame = CGRectMake(0, 0, width, 180 * _ratio);
        _moviePlayerController.controlStyle = LTCMovieControlStyleEmbedded;
        
        _Support_UserRote = NO;
        //        _gestureView.frame = CGRectMake(0, 180, 320, [UIScreen mainScreen].bounds.size.height - 180);
    }
}

#pragma mark - LTCMoviePlayerControllerDelegate


- (void)ltcMoviePlayerController:(LTCMoviePlayerController *)controller
         valibVideoCodeTypeArray:(NSArray *)codeTypeArray
            defaultVideoCodeType:(LTCVideoCodeType)defaultType
                       videoName:(NSString *)videoName
                 movieSourceType:(LTCMovieSourceType)sourceType{
    /*1.回调返回视频信息*/
    self.valibCodeArray = codeTypeArray;
    
}

- (LTCVideoCodeType)ltcPlayerDefaultVideoCodeType{
    if ([_valibCodeArray containsObject:[NSNumber numberWithInt:LTCVideoCodeTypeSD]]) {
        return LTCVideoCodeTypeSD; // 尝试设置为标清
    }
    return LTCVideoCodeTypeUnknown;
}

- (void)ltcMoviePlayerController:(LTCMoviePlayerController *)controller
          getCurrentPlayBackTime:(NSTimeInterval)time
               totalPlayBackTime:(NSTimeInterval)totalPlayBackTime
                 movieSourceType:(LTCMovieSourceType)sourceType{
    /*1. 记录点播的进度*/
    _backTime = time;
//    NSLog(@"-----backTime%f",_backTime);
}

- (void) ltcMoviePlayerController:(LTCMoviePlayerController *) controller playerStateChanged:(LTCMoviePlayerState) state sourceType:(LTCMovieSourceType)sourceType{
    NSLog(@"");
}

- (void) ltcMoviePlayerController:(LTCMoviePlayerController *) controller playerFailedWithErrorType:(LTCMoviePlayerErrorType) type sourceType:(LTCMovieSourceType)sourceType{
    
}

- (void) ltcPlayerViewTopControlBtnDidClicked:(LTCMoviePlayerController *) controller{
    [self ltcPlayerViewHalfScreenFullBtnClicked:controller];
}

// 强制旋转Controller
- (void) ltcPlayerViewHalfScreenFullBtnClicked:(LTCMoviePlayerController *) controller{
    
    _Support_UserRote = YES;
    if (!_m_bScreen) {
        [self.navigationController setNavigationBarHidden:YES animated:NO];
    }
    
    if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)])
    {
        NSNumber *num = [[NSNumber alloc] initWithInt:(_m_bScreen?UIInterfaceOrientationLandscapeRight:UIInterfaceOrientationPortrait)];
        [[UIDevice currentDevice] performSelector:@selector(setOrientation:) withObject:(id)num];
        [UIViewController attemptRotationToDeviceOrientation];
    }
    SEL selector=NSSelectorFromString(@"setOrientation:");
    NSInvocation *invocation =[NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
    [invocation setSelector:selector];
    [invocation setTarget:[UIDevice currentDevice]];
    int val = _m_bScreen?UIInterfaceOrientationLandscapeRight:UIInterfaceOrientationPortrait;
    [invocation setArgument:&val atIndex:2];
    [invocation invoke];
}

// 处理旋转

- (BOOL) shouldAutorotate{
    if (_Support_UserRote) {
        return YES;
       _scrollview.hidden = YES;
    }
    return NO;
}
- (void)dealloc {
    //记录观看时间
    NSLog(@"-----------------------backTime:%f",_backTime);
    NSString* backTime = [NSString stringWithFormat:@"%f",_backTime];
    [[NSUserDefaults standardUserDefaults]setObject:backTime forKey:self.videoUnique];
    //销毁timer
    [_timer invalidate];
    _timer = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}
@end
